// src/api/http.js
import axios from 'axios'
import router from '@/router'

// 创建 Axios 实例
const http = axios.create({
    baseURL: "http://localhost:8080/",
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

http.defaults.withCredentials = true;
// 请求拦截器
http.interceptors.request.use(
    (config) => {

        const token2 = localStorage.getItem("auth")
        if(token2){
            config.headers['token'] = `${token2}`;
        }
        // 处理文件上传
        if (config.data instanceof FormData) {
            config.headers['Content-Type'] = 'multipart/form-data'
        }

        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器
http.interceptors.response.use(
    (response) => {
        // 统一处理响应数据
        if (response.data && response.data.code === 200) {
            return response.data
        }
        return handleError(response.data)
    },
    (error) => {
        console.log(error)
        // 处理网络错误
        if (error.status === 401) {
            return handleError(error.response)
        }
        return Promise.reject(error)
    }
)

// 错误处理函数
function handleError(response) {
    // 统一错误码处理
    const errorMap = {
        401: '未授权，请重新登录',
        403: '拒绝访问',
        404: '资源未找到',
        500: '服务器错误',
        503: '服务不可用'
    }
    // 处理认证失败
    if (response.status === 401) {
        router.push('/admin/login')
    }

    // 抛出业务错误信息
    const errorMessage = response.msg || errorMap[response.code] || '未知错误'
    return {
        code: response.code,
        message: errorMessage,
        data: response.data
    };
}

// 封装常用请求方法
export default {
    get: (url, params, config) => http.get(url, { params, ...config }),
    post: (url, data, config) => http.post(url, data, config),
    put: (url, data, config) => http.put(url, data, config),
    delete: (url, config) => http.delete(url, config),
    upload: (url, file, config) => {
        const formData = new FormData()
        formData.append('file', file)
        return http.post(url, formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            ...config
        })
    }
}